//
//  NSArray+beyond.m
//  arraybeyond
//
//  Created by 辛路琦 on 2017/3/6.
//  Copyright © 2017年 xinluqi. All rights reserved.
//

#import "NSArray+beyond.h"
#import <objc/runtime.h>

@implementation NSArray (beyond)

+ (void)load {
    
    [super load];
    //  替换不可变数组中的方法
    Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
    Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(XLQ_objectAtIndex:));
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    //  替换可变数组中的方法
    Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
    Method newMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(XLQ_mutableObjectAtIndex:));
    method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);
}

- (id)XLQ_objectAtIndex:(NSUInteger)index {
    
    if (index > self.count - 1 || !self.count) {
       
        @try {
            return [self XLQ_objectAtIndex:index];
        } @catch (NSException *exception) {
            // throwOutException  抛出异常
            NSLog(@"数组越界...%@%@", [NSThread callStackSymbols], [self class]);
            
            return nil;
        } @finally {}
    }else {
        return [self XLQ_objectAtIndex:index];
    }
}

- (id)XLQ_mutableObjectAtIndex:(NSUInteger)index{
   
    if (index > self.count - 1 || !self.count) {
        
        @try {
            return [self XLQ_mutableObjectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  抛出异常
            NSLog(@"数组越界...");
            NSLog(@"数组越界...%@%@", [NSThread callStackSymbols], [self class]);

            return nil;
        } @finally {}
    }else {
        return [self XLQ_mutableObjectAtIndex:index];
    }
}
@end
